package com.gao.ranklist.controller;

import com.gao.ranklist.constant.Constants;
import com.gao.ranklist.service.HotSearchRanklistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 热搜排行榜
 */
@Controller
public class HotSearchRanklistController {

    @Autowired
    private HotSearchRanklistService hsrListService;

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 获取热榜数据
     */
    @PostMapping(value = "/rankList")
    @ResponseBody
    public Map<String, Object> rankList(@RequestParam(name = "type") String type) {
        Map<String, Object> map = new HashMap<>();
        Set rankList = new HashSet();
        String key = null;
        long hour = System.currentTimeMillis() / (1000 * 60 * 60);
        if ("hour".equals(type)) {
            key = Constants.HOT_SEARCH_HOUR_KEY + hour;
        } else if ("day".equals(type)) {
            key = Constants.HOT_SEARCH_DAY_KEY;
        } else if ("week".equals(type)) {
            key = Constants.HOT_SEARCH_WEEK_KEY;
        } else if ("month".equals(type)) {
            key = Constants.HOT_SEARCH_MONTH_KEY;
        }
        rankList = hsrListService.getHotSearchRankList(key, 0, 19);
        //设置跳转的视图 默认映射到 src/main/resources/templates/{viewName}.html
        map.put("status", 200);
        map.put("data", rankList);
        return map;
    }

    /**
     * 模拟搜索
     */
    @PostMapping(value = "/search")
    public String search(@RequestParam(name = "member") String value,
                         @RequestParam(name = "times") int times) {
        hsrListService.addHotSearchIndex(Constants.HOT_SEARCH, value, times);
        return "redirect:/";
    }
}

